<template>
    <div>
        <el-card shadow="hover" :body-style="{ padding: '20px' }">
            <!-- 添加按钮 -->
            <el-button type="primary" size="default" :icon="Plus" @click="addTrademark">添加</el-button>

            <!-- 表格 -->
            <el-table border style="margin:10px 0" :data="tmObj.records" v-loading="loading"
                element-loading-text="玩命加载中..." element-loading-background="rgba(122, 122, 122, 0.1)">
                <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
                <el-table-column label="品牌名称" prop="tmName"></el-table-column>
                <el-table-column label="品牌LOGO">
                    <template #="{row,$index}">
                        <a :title="row.tmName">
                            <img :src="row.logoUrl" alt="" style="width:100px; height: 60px;">
                        </a>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #="{row,$index}">
                        <el-button type="warning" size="small" :icon="Edit" @click="updateTrademark(row)"></el-button>
                        <el-button type="danger" size="small" :icon="Delete" @click="goDelete(row)"></el-button>

                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <el-pagination v-model:current-page="currentPage" :page-sizes="[3,5,7]" v-model:page-size="pageSize"
                layout=" prev, pager, next, jumper,->,sizes,total" :total="tmObj.total" background :pager-count="7"
                @current-change="getTrademark" @size-change="sizeHandler">
            </el-pagination>

            <!-- 点击添加弹出的对话框 -->
            <el-dialog v-model="dialogFormVisible" :title="tmTitle" draggable>
                <el-form style="width:80%" :model="form" label-width="90px" :rules="rules" ref="formRef">
                    <!-- 品牌名称 -->
                    <el-form-item label="品牌名称" prop="tmName">
                        <el-input v-model="form.tmName" autocomplete="off" />
                    </el-form-item>
                    <!-- 品牌LOGO -->
                    <el-form-item label="品牌LOGO" prop="logoUrl">
                        <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload"
                            :show-file-list="false" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="addOrUpdateTrademark">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </el-card>

    </div>
</template>

<script setup lang="ts">
import { reqTrademarkList, reqAddOrUpdateTrademark, reqDelateTrademark } from '@/api/product/trademark/trademark'
import type { trademarkResponseData, trademark } from '@/api/product/trademark/model/trademark'
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus
} from '@element-plus/icons-vue'
import { nextTick, onMounted, reactive, ref } from 'vue';
// 消息提示信息
import { ElMessage } from 'element-plus'
// 上传图片需要的钩子
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
// 控制loading效果响应式数据
let loading = ref<boolean>(false)
// 保存分页器当前页码
let currentPage = ref<number>(2)
// 保存当前页面显示几条
let pageSize = ref<number>(3)
let tmObj = reactive<trademarkResponseData>({
    total: 99,
    records: []
})
// 控制对话框的显示与隐藏
let dialogFormVisible = ref<boolean>(false)
// 定义添加品牌需要的数据
let form = reactive<trademark>({
    tmName: '',
    logoUrl: ''
})

// 定义对话框的标题名
let tmTitle = ref<string>('添加品牌')
// 存储form表单的实例
let formRef = ref<FormInstance>()
// 表单验证 规则
let rules = reactive<FormRules>({
    tmName: [
        { required: true, message: '请输入内容不能为空', trigger: 'blur' },
        { required: true, min: 2, max: 10, message: '输入的内容为2-10', trigger: 'change' },
    ],
    logoUrl: [
        { required: true, message: '请上传logo图片' }
    ]
})
// 组件挂载
onMounted(() => {
    // 发请求
    getTrademark()
})

// 获取品牌数据
const getTrademark = async (page: number = 1) => {
    // 发请求之前loading加载
    loading.value = true
    // 整理数据
    currentPage.value = page
    let result = await reqTrademarkList(currentPage.value, pageSize.value)
    // console.log(result);
    // 存储品牌数据
    tmObj.records = result.records
    // 存储总条数
    tmObj.total = result.total
    // 服务器数据回来加载效果消失
    loading.value = false
}
// 切换一页展示几条数据
const sizeHandler = (limit: number) => {
    // 整理数据
    pageSize.value = limit
    // 发请求
    getTrademark()
}

// 上传成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    // console.log(response);
    form.logoUrl = response.data
}
// 上传成功之前的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    //图片相关的信息
    //外层约束类型
    if (
        rawFile.type == "image/jpeg" ||
        rawFile.type == "image/png" ||
        rawFile.type == "image/gif"
    ) {
        //约束大小1024B->1K->1M->1G->1T
        if (rawFile.size / 1024 / 1024 <= 5) {
            return true;
        }
    } else {
        return false;
    }
}

//点击确定 添加或修改品牌信息
const addOrUpdateTrademark = async () => {
    // 全部字段进行校验
    formRef.value?.validate(async (success) => {
        if (success) {
            // 如果有id就修改 没有就是添加
            if (form.id) {
                try {
                    // 发请求
                    await reqAddOrUpdateTrademark(form)
                    // console.log(result);
                    // 发请求重新获取列表
                    getTrademark(currentPage.value)
                    // 隐藏对话框
                    dialogFormVisible.value = false
                    ElMessage({
                        message: '修改品牌成功',
                        type: 'success',
                    })
                } catch (error) {
                    ElMessage({
                        message: '修改品牌失败',
                        type: 'error',
                    })
                }
            } else {
                try {
                    // 发请求
                    await reqAddOrUpdateTrademark(form)
                    // console.log(result);
                    // 发请求重新获取列表

                    // 隐藏对话框
                    dialogFormVisible.value = false
                    getTrademark()
                    ElMessage({
                        message: '添加品牌成功',
                        type: 'success',
                    })
                } catch (error) {
                    ElMessage({
                        message: '添加品牌失败',
                        type: 'error',
                    })
                }
            }

        }

    })




}

// 点击添加 显示对话框
const addTrademark = () => {
    // 显示对话框
    dialogFormVisible.value = true
    tmTitle.value = '添加品牌'
    form.tmName = ''
    form.logoUrl = ''
    form.id = ''
    // 重置表单验证信息
    nextTick(() => {
        formRef.value?.resetFields()
    })
}

// 点击修改 显示对话框
const updateTrademark = (row: trademark) => {
    // 显示对话框
    dialogFormVisible.value = true
    // 修改对话框的标题名
    tmTitle.value = '修改品牌'
    // console.log(row);
    // 重置表单验证信息
    nextTick(() => {
        formRef.value?.resetFields()
        // 存储选中的品牌名称
        form.tmName = row.tmName
        // 存储选中的品牌logo
        form.logoUrl = row.logoUrl
        // 存储选中的品牌id
        form.id = row.id
    })
}
// 点击删除
const goDelete = async (row: trademark) => {
    console.log(row);
    try {
        // 发请求 删除品牌数据
        let result = await reqDelateTrademark(row)
        // console.log(result);
        // 重新获取商品列表
        getTrademark(currentPage.value)
        //删除成功提示信息
        ElMessage({
            message: `删除${row.tmName}成功`,
            type: 'success',
        })
    } catch (error) {
        ElMessage({
            message: '删除品牌失败',
            type: 'error',
        })
    }
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
    
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>